package test;

import org.junit.Test;
import java.util.*;

/**
 * array 和 list 之间的转换
 * 
 * @author Liu Huan
 */

public class ListToArray {
	
	List<String> stringList = new ArrayList(){{
		add("aa");
		add("bb");
	}};
	
	@Test
	public void testZero() {
		String[] str2 = stringList.toArray(new String[stringList.size()]);
		
		for (String string : str2) {
			System.out.println(string);
		}
	}
	
	@Test
	public void testOne() {
		String[] stringArray = (String[]) stringList.toArray();
		//java.lang.ClassCastException: java.lang.Object; cannot be cast to java.lang.String;
	}
	
	@Test
	public void testTwo() {
		String[] str1 = new String[1];
		String[] str2 = stringList.toArray(str1);
		
		System.out.println(str1 == str2);// false
		for (String string : str2) {
			System.out.println(string);
		}
	}
	
	@Test
	public void testThree() {
		String[] str1 = new String[stringList.size()];
		String[] str2 = stringList.toArray(str1);
		
		System.out.println(str1 == str2);// true
		for (String string : str2) {
			System.out.println(string);
		}
	}
	
	@Test
	public void testFour() {
		String[] str1 = new String[stringList.size()+2];
		String[] str2 = stringList.toArray(str1);
		
		System.out.println(str1 == str2);// true
		for (String string : str2) {
			System.out.println(string);
		}
	}
	
	List<int[]> list = new ArrayList<>();
	@Test
	public void testTwoArray(){
		list.add(new int[]{1,2,3});
		list.add(new int[]{4,5});
		
		int[][] result = list.toArray(new int[list.size()][]);
		for (int i = 0; i < result.length; i++) {
			System.out.print("[ ");
			for (int j = 0; j < result[i].length; j++) {
				System.out.print(result[i][j] + " ");
			}
			System.out.print("]");
			System.out.println();
		}
	}
	
}
